package cn.tedu.health.service.impl;

import cn.tedu.health.exception.ServiceException;
import cn.tedu.health.mapper.UserMapper;
import cn.tedu.health.pojo.entity.User;
import cn.tedu.health.response.StatusCode;
import cn.tedu.health.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService implements IUserService {

    @Autowired
    private UserMapper mapper;

    @Override
    public void registerUser(User user) {
        System.out.println(user);
        if (mapper.findByEmail(user.getEmail()) != null) {
            throw new ServiceException(StatusCode.EMAIL_ALREADY_EXISTS);
        }
        if (mapper.findByPhone(user.getPhone()) != null) {
            throw new ServiceException(StatusCode.PHONE_ALREADY_EXISTS);
        }
        mapper.insert(user);
    }

    @Override
    public User loginUser(String username, String password) {
        User user = mapper.findByUsername(username);
        if (user == null) {
            throw new ServiceException(StatusCode.USERNAME_ERROR);
        }
        if (user.getPassword().equals(password)) {
            throw new ServiceException(StatusCode.PASSWORD_ERROR);
        }
        return user;
    }
    @Override
    public User updateUser(User user) {
        User existingUser = mapper.findById(user.getId());
        if (existingUser == null) {
            throw new ServiceException(StatusCode.OPERATION_FAILED);
        }
        mapper.update(user);
        return user;
    }

    @Override
    public User getUserById(Long id) {
        User user = mapper.findById(id);
        if (user == null) {
            throw new ServiceException(StatusCode.OPERATION_FAILED);
        }
        return user;
    }
}
